package com.demo.phone.autohome;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : YU.TAN
 * @date : 2021/10/29 16:39
 */
public class ObjectToMapUtils {

    public static Map<String, String> objToMap(Object object) throws Exception {
        Map<String, String> result = new HashMap<>(16);
        Class<?> clazz = object.getClass();
        while (null != clazz.getSuperclass()) {
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                String fieldName = field.getName();
                //获取原来的访问控制权限
                boolean accessible = field.isAccessible();
                if (!accessible) {
                    //修改原来的访问控制权限
                    field.setAccessible(true);
                }
                Object value = field.get(object);
                //恢复原来的访问控制权限
                field.setAccessible(accessible);
                if (null != value && StringUtils.isNotBlank(value.toString())) {
                    //如果是List,将List转换为json字符串
                    if (value instanceof List) {
                        value = JSON.toJSONString(value);
                    }
                    result.put(fieldName, value.toString());
                }
            }
            clazz = clazz.getSuperclass();
        }
        return result;
    }
}
